// 栈 后进先出

// 创建基于数组的栈
class Stack {
  constructor() {
    //timers末尾为栈顶,数组头为栈底
    this.timers = []
  }
  push(item) {
    this.timers.push(item)
  }
  pop() {
    return this.timers.pop()
  }
  peek() {
    return this.timers[this.timers.length - 1]
  }
  isEmpty() {
    return this.timers.length === 0
  }
  clear() {
    this.timers = []
  }
  size() {
    return this.timers.length
  }
}
let stack = new Stack();
// console.log(stack.toString())
console.log(stack.isEmpty())
stack.push(5);
stack.push(8)
console.log(stack.peek())
stack.push(11)
console.log(stack.size())
console.log(stack.isEmpty())
stack.push(15)
stack.pop()
stack.pop()
// console.log(stack.size())
console.log(stack.timers)

// 创建基于对象的栈
class Stack1 {
  constructor() {
    this.count = 0;
    this.items = {}
  }
  toString() {
    if (this.isEmpty()) {
      return ''
    }
    let objString = `${this.items[0]}`; // {1} 
    for (let i = 1; i < this.count; i++) { // {2} 
      objString = `${objString},${this.items[i]}`; // {3} 
    }
    return objString;
  }
  push(ele) {
    this.items[this.count] = ele
    this.count++
  }
  isEmpty() {
    return this.count === 0

  }
  pop() {
    if (this.isEmpty()) {
      return undefined
    }
    this.count--
    const result = this.items[this.count]
    delete this.items[this.count]
    return result
  }
  peek() {
    if (this.isEmpty()) {
      return undefined
    }
    return this.items[this.count - 1]
  }
  size() {
    return this.count
  }
  clear() {
    this.count = 0
    this.items = {}
  }

}
/* 
除了 toString 方法，我们创建的其他方法的复杂度均为 O(1)，代表我们可以
直接找到目标元素并对其进行操作（push、pop 或 peek）。
*/
// let stack1 = new Stack1()
// stack1.push(1)
// stack1.push(2)
// console.log(stack1.items)
// console.log(stack1.toString())


function baseConverter(decNumber, base) {
  const remStack = new Stack();
  const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // {6} 
  let number = decNumber;
  let rem;
  let baseString = '';
  if (!(base >= 2 && base <= 36)) {
    return '';
  }
  while (number > 0) {
    rem = Math.floor(number % base);
    remStack.push(rem);
    number = Math.floor(number / base);
  }
  while (!remStack.isEmpty()) {
    baseString += digits[remStack.pop()]; // {7} 
  }
  return baseString;
}
console.log(baseConverter(10, 3),111)